#!/usr/bin/env bash

# Copyright (c) 2017  Zotero
#                     Center for History and New Media
#                     George Mason University, Fairfax, Virginia, USA
#                     http://zotero.org
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
ROOT_DIR="$( dirname "$DIR" )"

function usage {
	cat >&2 <<DONE
Usage: $0 -p platforms
Options
 -p PLATFORMS       [Required] Platforms to test (c=Chrome, f=Firefox, s=Safari)
 -s                 Skip build
 -x PATH            Path to browser executable
 -c                 Keep the browser open after tests have finished
DONE
	exit 1
}

# Require at least one platform
# Can technically pass these in as ENV_VARS instead of args, but undocumented in usage
while getopts "sp:x:c" opt; do
	case $opt in
		p)
			for i in `seq 0 1 $((${#OPTARG}-1))`
			do
				case ${OPTARG:i:1} in
					c) TEST_CHROME=1;;
					f) TEST_FX=1;;
					s) TEST_SAFARI=1;;
					*)
						echo "$0: Invalid platform option ${OPTARG:i:1}"
						usage
						;;
				esac
			done
			;;
		s)
			SKIP_BUILD=1
			;;
		x)
			export BROWSER_EXECUTABLE=$OPTARG
			;;
		c)
			export KEEP_BROWSER_OPEN=1
			;;
	esac
	shift $((OPTIND-1)); OPTIND=1
done

if [[ -z "$TEST_CHROME" ]] && [[ -z "$TEST_FX" ]] && [[ -z "$TEST_SAFARI" ]]; then
	usage
fi

if [ ! -z "$TEST_SAFARI" ]; then
	echo "Platform unimplemented"
	exit 1
fi

if [[ -z "$SKIP_BUILD" ]]; then
	$ROOT_DIR/build.sh -d
fi

if [[ ! -z "$TEST_CHROME" ]]; then
	export TEST_CHROME
elif [[ ! -z "$TEST_FX" ]]; then
	cd $ROOT_DIR/build/firefox
	zip -q -r /tmp/zoteroConnector.xpi *
	export TEST_FX
fi

$DIR/seleniumTests.js
